package com.controller;

import com.model.EmailShiti;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;
import javax.mail.internet.MimeMessage;

@Api(tags = "邮件接口")
@RestController
public class EmailShitiController {

    @Autowired
    private JavaMailSender jms;

    @Value("${spring.mail.username}")
    private String username;

    @RequestMapping(value = "/sendEmail",method = RequestMethod.POST)
    public String sendEmail(EmailShiti emailShiti) {

        System.out.println(emailShiti.toString());
        String str=null;
        try {
            //1.声明邮箱对象
            MimeMessage message=null;
            message=jms.createMimeMessage();
            MimeMessageHelper html=new MimeMessageHelper(message,true,"UTF-8");
            emailShiti.setFrom(username);

            //2.通过邮箱对象设置相关参数
            html.setFrom(username);
            html.setTo(emailShiti.getTo());
            html.setSubject(emailShiti.getSubject());
            String text=emailShiti.getText();

            System.out.println("TEXT:  ");
            System.out.println(text);
            System.out.println("=======");
            html.setText(text,true);

            System.out.println("CHAO: ");
            System.out.println(emailShiti.getChaoSend());
            System.out.println("========");
            if (emailShiti.getChaoSend()!=null) {
                System.out.println("OK！");
                System.out.println(emailShiti.getChaoSend().length());

                html.setCc(emailShiti.getChaoSend().split(","));

            }else {
                System.out.println("NOT OK！");
            }

            //3.发送邮件
            jms.send(message);
            str = "发送成功啦！";
        }catch (Exception e) {
//            System.out.println(e.getCause());
            System.out.println("邮件发送失败，原因是:"+e.getMessage());
            str="发送失败哦！";
        }
        return str;
    }
}
